<?php

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use App\Jobs\SendInvoiceEmail;
use App\Models\Domain\Domain;
use App\Models\Member\Member;
use App\Models\Service\EmailVerify;
use App\Models\Service\SMSVerify;
use App\Models\User\Gongdan;
use App\Models\User\Notice;
use Carbon\Carbon;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;

class PublicController extends Controller {
	//网站首页
	public function home() {
		//公告
		$notice = Notice::orderBy( 'created_at' )->paginate( 5 );
		//域名
		$domain = Domain::orderBy( 'created_at' )->paginate( 100 );

		return view( 'index', compact( 'notice', 'domain' ) );
	}

	public function domain() {
		$query     = \request()->except( [ '_token' ] );
		$query_str = '&' . 'keyword' . '=' . @$query['keyword'] . '&';
		$query_str .= 'skip' . '=' . @$query['skip'] . '&';
		$query_str .= 'hz' . '=' . @$query['hz'] . '&';
		$query_str .= 'icp_type' . '=' . @$query['icp_type'] . '&';
		$query_str .= 'provider' . '=' . @$query['provider'] . '&';
		$query_str .= 'city' . '=' . @$query['city'] . '&';
		$query_str .= 'price_start' . '=' . @$query['price_start'] . '&';
		$query_str .= 'price_end' . '=' . @$query['price_end'] . '&';
		$query_str .= 'length_start' . '=' . @$query['length_start'] . '&';
		$query_str .= 'length_end' . '=' . @$query['length_end'] . '&';

		if ( \request()->isMethod( 'POST' ) ) {
			//	dd( isset( $query['skip'] ) );
			$domain   = Domain::orderBy( 'created_at' )->
			where( 'domain', 'like', '%' . @$query['keyword'] . '%' )->
			where( 'domain', 'not like', isset( $query['skip'] ) ? '%' . @$query['skip'] . '%' : '' )->
			where( 'domain', 'like', '%' . @$query['hz'] )->
			where( 'icp_type', isset( $query['icp_type'] ) ? '=' : '!=', @$query['icp_type'] )->
			where( 'provider', 'like', '%' . $query['provider'] . '%' )->
			where( 'city', 'like', isset( $query['city'] ) ? '%' . $query['city'] . '%' : '%%' )->
			where( 'price', '>=', isset( $query['price_start'] ) ? $query['price_start'] : '' )->
			where( 'price', '<=', isset( $query['price_end'] ) ? $query['price_end'] : 99999999 )->
			whereRaw( 'LENGTH(domain)>= ? and LENGTH(domain)<= ?',
				[
					isset( $query['length_start'] ) ? $query['length_start'] : 1,
					isset( $query['length_end'] ) ? $query['length_end'] : 191
				] )->
			paginate( 10 );
			$provider = $query['provider'];

			return view( 'domain', compact( 'domain', 'provider', 'query_str' ) );
		}
		$provider = request()->get( 'provider' );

		if ( ! empty( $provider ) ) {
			//	$domain = DomainInduce::orderBy( 'created_at' )->where('provider',(request()->only('provider')))->paginate( 10 );
			$domain = Domain::orderBy( 'created_at' )->
			where( 'domain', 'like', '%' . @$query['keyword'] . '%' )->
			where( 'domain', 'not like', isset( $query['skip'] ) ? '%' . @$query['skip'] . '%' : '' )->
			where( 'domain', 'like', '%' . @$query['hz'] )->
			where( 'icp_type', isset( $query['icp_type'] ) ? '=' : '!=', @$query['icp_type'] )->
			where( 'provider', 'like', '%' . $query['provider'] . '%' )->
			where( 'city', 'like', isset( $query['city'] ) ? '%' . $query['city'] . '%' : '%%' )->
			where( 'price', '>=', isset( $query['price_start'] ) ? $query['price_start'] : '' )->
			where( 'price', '<=', isset( $query['price_end'] ) ? $query['price_end'] : 99999999 )->
			whereRaw( 'LENGTH(domain)>= ? and LENGTH(domain)<= ?',
				[
					isset( $query['length_start'] ) ? $query['length_start'] : 1,
					isset( $query['length_end'] ) ? $query['length_end'] : 191
				] )->
			paginate( 10 );
		} else {
			$domain = Domain::orderBy( 'created_at' )->paginate( 10 );
		}

		return view( 'domain', compact( 'domain', 'provider', 'query_str' ) );
	}

	public function notice() {
		$single = Notice::where( 'id', \request( 'id' ) )->first();
		$notice = Notice::orderBy( 'created_at' )->paginate( 5 );

		return view( 'notice', compact( 'single', 'notice' ) );
	}

	public function gongdan() {
		$user = \auth( 'admin' )->user();

		if ( \request()->isMethod( 'POST' ) ) {
			$validator = Validator::make(
				\request()->all(),
				[//            'username' => 'required|min:3|max:20|unique:App\User\User,username',
					'title'   => 'required',
					'content' => 'required',
				],
				[
					//'password2.same'  => '两次密码不一致!',
					//'vercode.captcha' => '验证码错误',
					'title.required'   => '请输入标题',
					'content.required' => '请输入内容',
				]
			);
			if ( $validator->fails() ) {
				$error      = collect( $validator->errors()->all() );
				$returnData = array(
					'code'  => '0',
					'msg'   => '验证失败',
					'data'  => $validator->errors()->all(),
					'error' => $error->toJson(),

				);

				return response()->json( $returnData, 200 );
			}
			$data            = request()->except( [ '_token' ] );
			$data['user_id'] = $user->id;
			$res             = Gongdan::create( $data );
			if ( $res ) {
				return response()->json( [ 'msg' => '提交成功!', 'code' => 0 ], 200 );
			} else {
				return response()->json( [ 'msg' => '提交失败!', 'code' => 400 ], 200 );
			}

		}

		return view( 'gongdan.gongdan' );
	}

	public function dgongdan() {
		$user = \auth( 'admin' )->user();
		$data = Gongdan::where( 'user_id', $user->id )->where( 'status', 0 )->paginate( 5 );

		return view( 'gongdan.dgongdan', compact( 'data' ) );
	}

	public function gdlist() {
		$user = \auth( 'admin' )->user();
		$data = Gongdan::where( 'user_id', $user->id )->paginate( 5 );

		return view( 'gongdan.gdlist', compact( 'data' ) );
	}

	public function gdinfo() {
		$user = \auth( 'admin' )->user();
		$gdh  = \request()->only( 'gdh' );
		if ( empty( $gdh ) ) {
			return response( '非法访问!' );
		}
		$data = Gongdan::where( 'id', $gdh )->first();


		return view( 'gongdan.gdinfo', compact( 'data' ) );
	}


	//面板首页
	public function index() {
//$info =geoip('127.0.0.1');
//$info =geoip('202.102.134.68');
// dd($info);

		return view( 'member.index' );
	}

	//欢迎页面
	public function welcome() {
		return view( 'manager.public.welcome' );
	}

	public function login( Request $request ) {

		if ( $request->isMethod('POST')) {
			$validator = Validator::make(
				$request->all(),
				[//            'username' => 'required|min:3|max:20|unique:App\User\User,username',
					'email'    => 'required',
					'password' => 'required',
					//	'vercode'  => 'captcha',
				],
				[ 'email.required' => '请输入邮箱', 'password.required' => '请输入密码', ]
			);
			if ( $validator->fails() ) {
				$error      = collect( $validator->errors()->all() );
				$returnData = array(
					'code'  => '0',
					'msg'   => '验证失败',
					'data'  => $validator->errors()->all(),
					'error' => $error->toJson(),

				);

				return response()->json( $returnData, 500 );
			}
			$data['email']    = $request->get( 'email' );
			$data['password'] = $request->get( 'password' );
			//$data['deleted']  = false; // 未删除用户
			//$data['status']   = '2'; //  1 禁用  2启用

			$result = Auth::guard( 'admin' )->attempt( $data );
			if ( $result ) {
				 Member::where( 'email', $data['email'] )->increment( 'login_count' );
				Member::where( 'email', $data['email'] )->update( [
					'last_login' => date( 'Y-m-d H:i:s' ),
					'last_ip'    => $request->ip()
				] );

				return $this->result_api( 200, 'success' );
			} else {
				return $this->result_api(
					400, 'error', [ 'error' => '用户名或密码错误!' ]
				);
			}

		}

		//return view( 'manager.public.login' );
		return view( 'login' );
	}

	public function logout() {
		auth( 'admin' )->logout();

		return redirect()->route( 'manager_login' );
	}

	public function reg( Request $request ) {
		if ( $request->isMethod( 'post' ) ) {
			$validator = Validator::make(
				$request->all(),
				[
					//            'username' => 'required|min:3|max:20|unique:App\User\User,username',
					//'phone'     => 'required|unique:App\Models\Member\Member,mobile',
					'email'     => 'required|unique:App\Models\Member\Member,email',
					//'vercode'   => 'required',
					'password'  => 'required',
					'password2' => 'same:password',
					//	'nickname'  => 'required|string',
					//	'agreement' => 'required',
					'captcha'   => 'required|captcha',
				], [
					'phone.required'     => '手机号必填',
					'phone.unique'       => '用户已存在',
					'email.required'     => '邮箱必填',
					'email.unique'       => '用户已存在',
					'vercode.required'   => '验证短信 必填',
					'password.required'  => '密码 必填',
					'password2.same'     => '两次密码不正确',
					'nickname.required'  => '昵称 必填!',
					'agreement.required' => '必须同意',
					'captcha.captcha'    => '图形验证码错误',
					'captcha.required'   => '图形验证码必填',
				]
			);

			if ( $validator->fails() ) {
				$error      = collect( $validator->errors()->all() );
				$returnData = array(
					'code'  => '0',
					'msg'   => '验证失败',
					'data'  => $validator->errors()->first(),
					'error' => $error->toJson(),

				);

				return response()->json( $returnData, 500 );
			}


			//创建账号
			$data             = $request->only( 'password', 'email', 'qq', 'wechat' );
			$data['password'] = bcrypt( $data['password'] );
			$res              = Member::create( $data );

			if ( $res ) {
				//注册成功!  直接登录
				// $auth = Auth::attempt($request->only('username', 'password'));
				$auth = Auth::guard( 'admin' )->attempt(
					[
						'email'    => $request->get( 'email' ),
						'password' => $request->get( 'password' )
					]
				);

				return $this->result_api( 200, 'success', [ $auth ] );
			} else {
				//注册失败
				return $this->result_api( 400, 'error', [ 'error' => '注册失败!' ] );
			}

		}

		//注册页面  GET
		//return view( 'manager.public.reg' );
		return view( 'reg' );
	}

	//send  password-email
	public function zhaohuipw( Request $request ) {
		if ( $request->isMethod( 'post' ) ) {
			$validator = Validator::make(
				$request->all(),
				[
					//            'username' => 'required|min:3|max:20|unique:App\User\User,username',
					//'phone'     => 'required|unique:App\Models\Member\Member,mobile',
					//'email'     => 'required|unique:App\Models\Member\Member,email',
					'email'   => 'required|email',
					//'vercode'   => 'required',
					//	'password'  => 'required',
					//	'password2' => 'same:password',
					//	'nickname'  => 'required|string',
					//	'agreement' => 'required',
					'captcha' => 'required|captcha',
				], [
					'phone.required'     => '手机号必填',
					'phone.unique'       => '用户已存在',
					'email.required'     => '邮箱必填',
					'email.email'        => '不是有效的邮箱地址',
					'email.unique'       => '用户已存在',
					'vercode.required'   => '验证短信 必填',
					'password.required'  => '密码 必填',
					'password2.same'     => '两次密码不正确',
					'nickname.required'  => '昵称 必填!',
					'agreement.required' => '必须同意',
					'captcha.captcha'    => '图形验证码错误',
					'captcha.required'   => '图形验证码必填',
				]
			);

			if ( $validator->fails() ) {
				$error      = collect( $validator->errors()->all() );
				$returnData = array(
					'code'  => '0',
					'msg'   => '验证失败',
					'data'  => $validator->errors()->first(),
					'error' => $error->toJson(),

				);

				return response()->json( $returnData, 500 );
			}

			$user_email = $request->get( 'email' );
			$user       = Member::where( 'email', $user_email )->first();
			if ( is_null( $user ) ) {
				return $this->result_api( 400, 'error', [ 'error' => '未注册邮箱' ] );
			}
			$token        = Str::random( 40 );
			$email_verify = EmailVerify::where( 'email', $user_email )->first();

			if ( is_null( $email_verify ) ) {
				EmailVerify::create( [
					'email'    => $user->email,
					'token'    => $token,
					'end_time' => date( 'Y-m-d H:i:s', time() + 3600 )
				] );
			} else {
				// echo '更新';
				$email_verify->update( [
					'token'    => $token,
					'end_time' => date( 'Y-m-d H:i:s', time() + 3600 )
				] );


			}
			//模板发送
			Mail::send( 'public.email.password_reset_email', [
				'username' => '尊敬的会员',
				'site_name'     => config('base.email.MAIL_FROM_NAME',config('app.name')),
				'link'     => url( 'member/password/reset' ) . '?token=' . $token . '&email=' . $user_email
			],
				function ( $message ) use ( $user_email ) {
					$to = $user_email;
					$message->to( $to )->subject( '重置密码通知' );
				} );

			if ( count( Mail::failures() ) < 1 ) {
				return $this->result_api( 200, 'success' );
			} else {
				return $this->result_api( 400, 'error', [ 'error' => '发送邮件失败，请重试！' ] );
			}

		}

		return view( 'zhaohuipw' );
	}

	public function forget( Request $request ) {
		if ( $request->isMethod( 'post' ) ) {
			//修改密码请求
			if ( $request->get( 'token' ) != '' ) {
				$validator = Validator::make(
					$request->all(),
					[//            'username' => 'required|min:3|max:20|unique:App\User\User,username',
						//'phone'     => 'required|unique:App\Models\Member\Member,mobile',
						'phone'    => 'required|exists:App\Models\Service\SMSVerify,phone',
						'token'    => 'required|exists:App\Models\Service\SMSVerify,token',
						'password' => 'required',
						'repass'   => 'same:password',

						//	'captcha' => 'required|captcha',
						//'vercode'  => 'required',
						//	'password'  => 'required',
						//	'repass'    => 'same:password',

					], [
						'phone.required'     => '手机号 必填',
						'phone.exists'       => '手机号 错误',
						'token.required'     => '令牌 错误',
						'token.exists'       => '令牌 错误',
						'vercode.required'   => '验证短信 必填',
						'password.same'      => '密码 必填',
						'repass.same'        => '确认密码 必填',
						'nickname.required'  => '昵称 必填!',
						'agreement.required' => '必须同意',
						'captcha.captcha'    => '图形验证码错误',
					]
				);
				if ( $validator->fails() ) {
					$error      = collect( $validator->errors()->all() );
					$returnData = array(
						'code'  => '0',
						'msg'   => '验证失败',
						'data'  => $validator->errors()->all(),
						'error' => $error->toJson(),

					);

					return response()->json( $returnData, 500 );
				}

				$res = Member::where( 'mobile',
					$request->get( 'phone' ) )->update( [ 'password' => bcrypt( $request->get( 'password' ) ) ] );
				if ( $res ) {
					SMSVerify::where( 'phone', $request->get( 'phone' ) )->delete();

					return response()->json( [ 'msg' => 'success', 'code' => 0 ], 200 );
				} else {
					return $this->result_api( 400, 'error', [ 'error' => '修改失败!' ] );
				}
			}
			$validator = Validator::make(
				$request->all(),
				[//            'username' => 'required|min:3|max:20|unique:App\User\User,username',
					//'phone'     => 'required|unique:App\Models\Member\Member,mobile',
					'phone'   => 'required|exists:App\Models\Service\SMSVerify,phone',
					//	'captcha' => 'required|captcha',
					'vercode' => 'required',
					//	'password'  => 'required',
					//	'repass'    => 'same:password',

				], [
					'phone.required'     => '手机号 必填',
					'phone.exists'       => '短信验证码 错误',
					'vercode.required'   => '验证短信 必填',
					'password.same'      => '密码 必填',
					'repass.same'        => '确认密码 必填',
					'nickname.required'  => '昵称 必填!',
					'agreement.required' => '必须同意',
					'captcha.captcha'    => '图形验证码错误',
				]
			);
			if ( $validator->fails() ) {
				$error      = collect( $validator->errors()->all() );
				$returnData = array(
					'code'  => '0',
					'msg'   => '验证失败',
					'data'  => $validator->errors()->all(),
					'error' => $error->toJson(),

				);

				return response()->json( $returnData, 500 );
			}
			//短信验证
			$sms_verify = SMSVerify::where( 'phone', $request->get( 'phone' ) )->first();
			if ( $sms_verify->verify == $request->get( 'vercode' ) ) {
				return response()->json( [
					'msg'   => 'success',
					'code'  => 0,
					'token' => $sms_verify->token,
					'phone' => $sms_verify->phone
				], 200 );
			} else {
				return $this->result_api( 400, 'error', [ 'error' => '验证失败!' ] );
			}

			//创建账号
			$data              = $request->only( 'phone', 'password', 'nickname' );
			$data['username']  = $data['phone'];
			$data['mobile']    = $data['phone'];
			$data['nick_name'] = $data['nickname'];
			$data['password']  = bcrypt( $data['password'] );
			$res               = Member::create( $data );

			if ( $res ) {
				//注册成功!  直接登录
				// $auth = Auth::attempt($request->only('username', 'password'));
				$auth = Auth::guard( 'admin' )->attempt(
					[
						'mobile'   => $request->get( 'phone' ),
						'password' => $request->get( 'password' )
					]
				);

				return $this->result_api( 200, 'success', [ $auth ] );
			} else {
				//注册失败
				return $this->result_api( 400, 'error', [ 'error' => '注册失败!' ] );
			}

		}

		return view( 'manager.public.forget' );
	}

	public function sendSMS( Request $request ) {

		$validator = Validator::make(
			$request->all(),
			[//            'username' => 'required|min:3|max:20|exists:App\User\User,username',
				'phone'   => 'required|min:11|max:11|exists:App\Models\Manager\Manager,mobile',
				'captcha' => 'required|min:4|max:4|captcha',
			], [
				'phone.required'     => '手机号 必填',
				'phone.exists'       => '手机号 错误',
				'phone.min'          => '手机号 错误',
				'phone.max'          => '手机号 错误',
				'vercode.required'   => '验证短信 必填',
				'password.same'      => '密码 必填',
				'repass.same'        => '确认密码 必填',
				'nickname.required'  => '昵称 必填!',
				'agreement.required' => '必须同意',
				'captcha.captcha'    => '验证码错误',
				'captcha.required'   => '验证码错误',
				'captcha.min'        => '验证码错误',
				'captcha.max'        => '验证码错误',
			]
		);
		if ( $validator->fails() ) {
			$error      = collect( $validator->errors()->all() );
			$returnData = array(
				'code'  => '0',
				'msg'   => '失败',
				'data'  => $validator->errors()->all(),
				'error' => $error->toJson(),

			);

			return response()->json( $returnData, 500 );
		}

		$AccessKey    = 'LTAI4G48j5GkXhABzk5oMw6a';
		$Secret       = '88DNklJqUQKY7aRXsXdufmY2pURRH2';
		$SignName     = '阿里云短信测试专用'; //短信签名
		$TemplateCode = 'SMS_204990279'; //模板ID
		$code         = mt_rand( 1000, 9999 );    //验证码
		$token        = Str::random( 40 );
		$end_time     = date( 'Y-m-d H:i:s', time() + 3600 );

		$sms_verify = SMSVerify::where( 'phone', $request->get( 'phone' ) )->first();
		if ( is_null( $sms_verify ) ) {
			SMSVerify::create( [
				'username' => $request->get( 'phone' ),
				'phone'    => $request->get( 'phone' ),
				'verify'   => $code,
				'token'    => $token,
				'end_time' => $end_time
			] );
		} else {
			// echo '更新';
			$sms_verify->update( [
				'verify'   => $code,
				'token'    => $token,
				'end_time' => $end_time
			] );
		}
//
//		AlibabaCloud::accessKeyClient($AccessKey, $Secret)
//		            ->regionId('cn-hangzhou')
//		            ->asDefaultClient();
//
//		try {
//			$result = AlibabaCloud::rpc()
//			                      ->product('Dysmsapi')
//				// ->scheme('https') // https | http
//				                  ->version('2017-05-25')
//			                      ->action('SendSms')
//			                      ->method('POST')
//			                      ->host('dysmsapi.aliyuncs.com')
//			                      ->options([
//				                      'query' => [
//					                      'RegionId' => "cn-hangzhou",
//					                      'PhoneNumbers' => $user->mobile,
//					                      'SignName' => $SignName,
//					                      // 'TemplateCode' => $TemplateCode,
//					                      'TemplateCode' => "SMS_204990279",
//					                      'TemplateParam' => json_encode(['code' => $code]),
//					                      // 'TemplateParam' =>  "{code:1234}",
//				                      ],
//			                      ])
//			                      ->request();
//			print_r($result->toArray());
//			return $this->result_api(200, 'success');
//		} catch (ClientException $e) {
//			//   echo $e->getErrorMessage() . PHP_EOL;
//			return $this->result_api(400, 'error', ['error' => $e->getErrorMessage()]);
//		} catch (ServerException $e) {
//			//  echo $e->getErrorMessage() . PHP_EOL;
//			return $this->result_api(400, 'error', ['error' => $e->getErrorMessage()]);
//		}
		return response()->json( [ 'msg' => 'success', 'code' => 0 ], 200 );
	}

	//重置密码
	public function passwordReset( Request $request ) {
		if ( $request->isMethod( 'post' ) ) {
			$validator = Validator::make(
				$request->all(),
				[
					//            'username' => 'required|min:3|max:20|unique:App\User\User,username',
					//'phone'     => 'required|unique:App\Models\Member\Member,mobile',
					//'email'     => 'required|unique:App\Models\Member\Member,email',
					'email'     => 'required|email',
					//'vercode'   => 'required',
					//	'password'  => 'required',
					//	'password2' => 'same:password',
					//	'nickname'  => 'required|string',
					//	'agreement' => 'required',
					//'captcha' => 'required|captcha',
					'password'  => 'required|min:6',
					'password2' => 'same:password',
					'token'     => 'required',
				], [
					'phone.required'     => '手机号必填',
					'phone.unique'       => '用户已存在',
					'email.required'     => '邮箱必填',
					'email.email'        => '不是有效的邮箱地址',
					'email.unique'       => '用户已存在',
					'vercode.required'   => '验证短信 必填',
					'password2.same'     => '两次密码不正确',
					'nickname.required'  => '昵称 必填!',
					'agreement.required' => '必须同意',
					'captcha.captcha'    => '图形验证码错误',
					'captcha.required'   => '图形验证码必填',
					'password.required'  => '请输入密码',
					'password2.required' => '请输入密码',
					'token.required'     => '令牌错误',
				]
			);

			if ( $validator->fails() ) {
				$error      = collect( $validator->errors()->all() );
				$returnData = array(
					'code'  => '0',
					'msg'   => '验证失败',
					'data'  => $validator->errors()->first(),
					'error' => $error->toJson(),

				);

				return response()->json( $returnData, 500 );
			}

			$email_verify = EmailVerify::where( 'email', $request->get( 'email' ) )->
			where( 'token', $request->get( 'token' ) )->
			where( 'end_time', '>', date( 'Y-m-d H:i:s' ) )->
			first();


			if ( is_null( $email_verify ) ) {
				return $this->result_api( 400, 'error', [ 'error' => '验证错误' ] );
			}
			$user = Member::where( 'email', $email_verify->email )->first();
			$res  = $user->update( [ 'password' => bcrypt( $request->get( 'password' ) ) ] );
			if ( $res ) {
				$email_verify->delete();

				return $this->result_api( 200, 'success' );
			} else {
				return $this->result_api( 400, 'error', [ 'error' => '修改失败!' ] );
			}

		}


		return view( 'password-reset' );
	}

	//无访问权限提示
	public function noAccess() {
		return view( 'manager.public.no_access' );
	}

    public function queue()
    {
       // SendInvoiceEmail::dispatch()->delay(Carbon::now()->addMinutes(1));
      //  $this->dispatch(new SendInvoiceEmail());
     //   var_dump('queue');
        //$job = (new Test($test))->onQueue('队列名称');
        $job = (new SendInvoiceEmail());
        dispatch($job);
	}
}
